package org.common;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;

/**
 * HBase工具类 - 提供HBase连接和基本表操作
 */
public class MyHBase {
    private Connection connection;

    /**
     * 获取HBase连接
     * @return HBase连接对象
     * @throws IOException 如果连接失败
     */
    public Connection getConnection() throws IOException {
        if (connection == null || connection.isClosed()) {
            Configuration conf = HBaseConfiguration.create();
            conf.set("hbase.zookeeper.quorum", "192.168.80.128,192.168.80.129,192.168.80.130");
            connection = ConnectionFactory.createConnection(conf);
        }
        return connection;
    }

    /**
     * 检查表是否存在
     * @param tableName 表名
     * @return 表是否存在
     * @throws IOException 如果检查失败
     */
    public boolean tableExists(String tableName) throws IOException {
        try (Admin admin = getConnection().getAdmin()) {
            return admin.tableExists(TableName.valueOf(tableName));
        }
    }

    /**
     * 创建表
     * @param tableName 表名
     * @param columnFamilies 列族数组
     * @throws IOException 如果创建失败
     */
    public void createTable(String tableName, String... columnFamilies) throws IOException {
        try (Admin admin = getConnection().getAdmin()) {
            TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(TableName.valueOf(tableName));
            for (String cf : columnFamilies) {
                builder.setColumnFamily(ColumnFamilyDescriptorBuilder.of(cf));
            }
            admin.createTable(builder.build());
        }
    }

    /**
     * 关闭连接
     */
    public void close() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}